/**
 * Project Name:MoneyBag
 * File Name   :UserController.java
 * Package Name:com.fu.moneybag.controller
 * Date        :2015年12月15日 下午10:10:42
 * Author      :Samfu
 * Blog        :http://www.fulishang.win
 * Copyright (c) 2015, flsmgf@163.com All Rights Reserved.
 *
 */

package com.fu.moneybag.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.fu.moneybag.entity.Article;
import com.fu.moneybag.entity.User;
import com.fu.moneybag.service.ArticleService;
import com.fu.moneybag.service.ArticleTypeService;
import com.fu.moneybag.service.UserService;
import com.fu.moneybag.utils.Constant;

@Controller
@RequestMapping("/user")
public class UserController {

	// 添加logger to enable debug
	private Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	UserService userService;

	@Autowired
	ArticleService articleService;

	@Autowired
	ArticleTypeService articleTypeService;

	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpSession userSession) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		return userService.loginService(username, password, userSession, request);

	}

	// 显示用户首页
	@RequestMapping("/userindex")
	public String index(HttpServletRequest request, HttpSession session) {
		return "userindex";
	}

	// 显示用户首页，根据用户id跳转
	@RequestMapping("/index")
	public String userIndex(HttpServletRequest request, HttpSession session) {
		return userService.indexService(request, session);
	}

	// 退出登陆
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		logger.info("用户退出，销毁session。。。");
		// 销毁session
		session.invalidate();
		return "login";
	}

	// 跳转到用户注册页面
	@RequestMapping("register")
	public String register(HttpServletRequest request) {

		return "register";
	}

	// 添加新用户
	@RequestMapping("/addUser")
	public String addUser(HttpServletRequest request, HttpSession session) {

		String username = request.getParameter("name");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		// 检查用户是否已经存在
		User user = userService.getUserByUserName(username);
		if (user == null) {
			logger.info("用户不存在，注册继续");
			int addUserResult = userService.addUser(username, password, email);

			logger.info("添加用户结果： " + addUserResult);

			if (addUserResult == 1) {// 添加用户成功，跳转到用户首页
				User newUser = userService.getUserByUserName(username);
				session.setAttribute("user", newUser);
				return "redirect:userindex";
			} else {
				request.setAttribute("error", "注册用户失败，请重试！");
				return "register";
			}

		} else {
			logger.info("用户已经存在，请重新注册或者直接登录");
			request.setAttribute("error", "用户已经存在，请重新注册或者直接登录");
			return "register";
		}

	}

	// 检验用户是否已经存在
	@RequestMapping("/checkUserExist")
	public void checkUserExist(HttpServletRequest request, HttpServletResponse response) {
		String userName = request.getParameter("userName");
		User user = userService.checkIfUserExist(userName);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;
		try {
			out = response.getWriter();

			if (user == null) {
				out.print("用户名可以使用");
			} else {
				out.println("用户名已被注册");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 获取用户信息
	@RequestMapping("/userProfile")
	public String showUserProfile(HttpServletRequest request, HttpSession session) {
		// check if session exist
		User user = (User) session.getAttribute("user");

		if (user == null) {
			return "login";
		}
		logger.info("当前用户名： " + user.getUserName());
		// User user = userService.getUserByUserName(username);
		session.setAttribute("user", user);
		return "userProfile";
	}

	// 更新用户名
	@RequestMapping("/updateUserName")
	public String updateUserName(HttpServletRequest request, String username, HttpSession session) {
		logger.info("用户请求参数：" + ", username: " + username);
		User user = this.checkUserSession(session);
		if (user == null){
			return "login";
		}
		int succeed = userService.updateUserName(user.getUserId(), username);
		if (succeed == 1) {
			User user1 = userService.getUserByUserName(username);
			session.setAttribute("user", user1);
			request.setAttribute("succeedName", "更新用户名成功！");
		} else {
			request.setAttribute("errorName", "更新用户名出错！");
		}
		return "userProfile";
	}

	// 更新密码
	@RequestMapping("/updateUserPassword")
	public String updateUserPassword(HttpServletRequest request, String password, HttpSession session) {
		logger.info("用户请求参数：" + ", password: " + password);
		User user = this.checkUserSession(session);
		if (user == null){
			return "login";
		}
		int succeed = userService.updateUserPassword(user.getUserId(), password);
		if (succeed == 1) {
			User user1 = userService.getUserById(user.getUserId());
			session.setAttribute("user", user1);
			request.setAttribute("succeedPassword", "更新密码成功！");

		} else {
			request.setAttribute("errorPassword", "更新密码出错！");
		}
		return "userProfile";
	}

	// 更新邮箱
	@RequestMapping("/updateUserEmail")
	public String updateUserEmail(HttpServletRequest request, String email, HttpSession session) {
		logger.info("用户请求参数：" + ", email：" + email);
		User user = this.checkUserSession(session);
		if (user == null){
			return "login";
		}
		int succeed = userService.updateUserEmail(user.getUserId(), email);
		if (succeed == 1) {
			User user1 = userService.getUserById(user.getUserId());
			session.setAttribute("user", user1);
			request.setAttribute("succeedEmail", "更新邮箱成功！");
		} else {
			request.setAttribute("errorEmail", "更新邮箱出错！");
		}
		return "userProfile";
	}

	// 更新头像
	@RequestMapping("/updateUserAvartar")
	public String updateUserAvartar(HttpServletRequest request, MultipartFile file, HttpSession session) {
		logger.info("用户请求更改头像－－开始");
		User user = this.checkUserSession(session);
		if (user == null){
			return "login";
		}
		int succeed = userService.updateUserAvartar(request, user.getUserId(), file);
		if (succeed == 1) {
			User user1 = userService.getUserById(user.getUserId());
			session.setAttribute("user", user1);
			request.setAttribute("succeedAvartar", "更新头像成功！");
		} else {
			request.setAttribute("errorAvartar", "更新头像出错！");
		}
		return "userProfile";
	}
	
	//session checking
	public User checkUserSession(HttpSession session){
		User user = (User) session.getAttribute("user");
		return user;
	}
}
